from tw.api import Widget, JSLink, CSSLink, JSSource, CSSSource
from tw.extjs import all, all_debug

__all__ = ["UploadDialog", "upload_dialog_css", "upload_dialog_js", "upload_dialog_js_debug", "upload_panel_css"]

# declare your static resources here

upload_dialog_css = CSSLink(modname=__name__,
			filename='static/css/Ext.ux.UploadDialog.css')
upload_panel_css = CSSLink(modname=__name__,
			filename='static/css/upload_panel.css')
upload_dialog_js_debug = JSLink(modname=__name__,
			filename='static/Ext.ux.UploadDialog.js', javascript=[all_debug], css =[upload_dialog_css, upload_panel_css])
upload_dialog_js = JSLink(modname=__name__,
			filename='static/Ext.ux.UploadDialog.packed.js', javascript=[all])


class UploadJS(JSSource):
    _resource = []
    source_vars = ["upload_url"]
    src1 = """
var UploadDialogController = function()
{
  var dialog = null;  
  var button = null;
    """
    src2 = """
  var file_list_tpl = new Ext.Template(
    "<div class='file-list-entry'>File {name} successfuly uploaded.</div>"
  );
  file_list_tpl.compile();
    """
    src3 = """

  function hideLoadingMask()
  {
    var loading = Ext.get('loading');
    var mask = Ext.get('loading-mask');
    mask.remove();
    loading.remove();
    Ext.get(document.body).setStyle('overflow', 'visible');
  }

  function getDialog()
  {
    if (!dialog) {
      dialog = new Ext.ux.UploadDialog.Dialog({
        url: '${upload_url}',
        reset_on_hide: false,
        allow_close_on_upload: true,
        upload_autostart: true,
        post_var_name: 'upload'
      });
      
      dialog.on('uploadsuccess', onUploadSuccess);
    }
    return dialog;
  }
  
  function showDialog(button)
  {
    getDialog().show(button.getEl());
  }
  
  function onUploadSuccess(dialog, filename, resp_data)
  {
    var parts = filename.split("/");
    if (parts.length == 1) {
      filename = parts[0];
    }
    else {
      filename = parts.pop();
    }
    file_list_tpl.append('file-list', {name: filename});
  }
  
  return {
    init : function()
    {
      Ext.QuickTips.init();

      button = new Ext.Button({
        renderTo: 'show-dialog-btn',
        id: 'show-button',
        text: 'Show dialog',
        handler: showDialog
      });

      hideLoadingMask();
      Ext.get(document.body).setStyle('overflow', 'auto');
    }
  }
}();

Ext.BLANK_IMAGE_URL = '../ExtJS/resources/images/default/s.gif';
Ext.onReady(UploadDialogController.init);
    """
    src = src1 + src3
    template_engine = "genshi"
    javascript = [upload_dialog_js]
    def update_params(self, d):
        for param in self.source_vars:
            value = getattr(self, param)
            if isinstance(value, bool):
                d[param] = str(value).lower()
        super(UploadJS, self).update_params(d)

upload_js = UploadJS()

class UploadDialog(Widget):
    upload_js_obj = UploadJS
    template = """
<div id="loading-mask"
	style="width:100%;height:100%;background:#c3daf9;
	position:absolute;z-index:20000;left:0;top:0;">&#160;</div>
<div id="loading" style="z-index: 20001; position: absolute">
 <div class="loading-indicator">
   <img src="/toscawidgets/resources/tw.extuploaddialog.widgets/static/images/loading.gif"
	style="width:16px; height:16px; vertical-align: middle" alt="Loading indicator" />
   &#160;Loading
 </div>
</div>
<div id='demo-panel'>
  <h3>${panel_header}</h3>

  <div id='file-list'></div>
  <div id='show-dialog-btn'>
  </div>
</div>
    """

    css_src = """
    #loading-mask 
    {
      width:100%;
      height:100%;
      background:#c3daf9;
      position:absolute;
      z-index:20000;
      left:0px;
      top:0px;
    }
    
    #loading 
    {
      position:absolute;
      left:42%;
      top:40%;
      border:1px solid #6593cf;
      padding:2px;
      background:#c3daf9;
      width:200px;
      text-align:center;
      z-index:20001;
    }
    
    #loading .loading-indicator 
    {
      border:1px solid #a3bad9;
      background: white;
        background-position: 15px center;
      color:#003366;
      font:bold 13px tahoma,arial,helvetica;
      padding:10px;
      margin:0;
    }
    """
    upload_css = CSSSource(src=css_src)

    javascript = [upload_dialog_js]
    css = [upload_dialog_css, upload_panel_css, upload_css]

    params = ["upload_url", "panel_header"]
    js_params = ["upload_url"]
    panel_header = "File Uploader"

    def __init__(self, id=None, parent=None, children=[], **kw):
        """Initialize the widget here. The widget's initial state shall be
        determined solely by the arguments passed to this function; two
        widgets initialized with the same args. should behave in *exactly* the
        same way. You should *not* rely on any external source to determine
        initial state."""
        super(UploadDialog, self).__init__(id, parent, children, **kw)
        d = {}
        for param in self.js_params:
            value = getattr(self, param)
            if value is not None:
                d[param] = getattr(self, param)
        upload_js = self.upload_js_obj(**d)
        self.javascript.append(upload_js)

    def update_params(self, d):
        """This method is called every time the widget is displayed. It's task
        is to prepare all variables that are sent to the template. Those
        variables can accessed as attributes of d."""
        super(UploadDialog, self).update_params(d)
